<template>
  <div class="comment-item" :class="{ 'is-reply': comment.level > 1 }">
    <!-- 评论主体 -->
    <div class="comment-main">
      <!-- 用户头像 -->
      <div class="comment-avatar">
        <el-avatar
          :size="comment.level === 1 ? 36 : 32"
          :src="comment.author?.avatar"
          :alt="comment.author?.nickName"
        >
          <IconifyIconOnline icon="ep:user-filled" />
        </el-avatar>
      </div>

      <!-- 评论内容 -->
      <div class="comment-content">
        <!-- 用户信息 -->
        <div class="comment-meta">
          <span class="user-name">{{ comment.author?.nickName }}</span>

          <!-- 回复提示 -->
          <span v-if="comment.replyToUser" class="reply-to">
            回复 @{{ comment.replyToUser.nickName }}
          </span>

          <span class="comment-time">
            {{ formatTime(comment.createTime) }}
          </span>

          <!-- 敏感词标识 -->
          <el-tag v-if="comment.isSensitive" size="small" type="warning">
            敏感内容
          </el-tag>
        </div>

        <!-- 评论文本 -->
        <div class="comment-text">
          {{ comment.content }}
        </div>

        <!-- 操作按钮 -->
        <div class="comment-actions">
          <!-- 点赞按钮 -->
          <el-button
            text
            size="small"
            :class="{ 'is-liked': comment.isLiked }"
            :loading="comment.isLiking"
            @click="handleLike"
          >
            <IconifyIconOnline
              :icon="comment.isLiked ? 'ep:thumb-up-filled' : 'ep:thumb-up'"
              :size="14"
            />
            {{ formatNumber(comment.likeCount) }}
          </el-button>

          <!-- 回复按钮 -->
          <el-button
            v-if="comment.level === 1"
            text
            size="small"
            @click="toggleReply"
          >
            <IconifyIconOnline icon="ep:chat-dot-round" :size="14" />
            回复
          </el-button>

          <!-- 删除按钮（仅自己的评论） -->
          <el-button
            v-if="canDelete"
            text
            size="small"
            type="danger"
            @click="handleDelete"
          >
            <IconifyIconOnline icon="ep:delete" :size="14" />
            删除
          </el-button>
        </div>

        <!-- 回复表单 -->
        <div v-if="showReplyForm" class="reply-form">
          <comment-form
            :article-id="articleId"
            :reply-to="{
              commentId: comment.id,
              userId: comment.author.userId,
              nickName: comment.author.nickName
            }"
            @submit="handleReplySubmit"
            @cancel-reply="toggleReply"
          />
        </div>
      </div>
    </div>

    <!-- 子评论列表 -->
    <div
      v-if="comment.children && comment.children.length > 0"
      class="comment-replies"
    >
      <comment-item
        v-for="reply in comment.children"
        :key="reply.id"
        :comment="reply"
        :article-id="articleId"
        @reply="$emit('reply', $event)"
        @like="$emit('like', $event.commentId, $event.liked)"
        @delete="$emit('delete', $event)"
      />

      <!-- 更多回复提示 -->
      <div v-if="comment.hasMoreChildren" class="more-replies">
        <el-button text size="small" @click="$emit('load-replies', comment.id)">
          查看更多 {{ comment.childrenTotal - comment.children.length }} 条回复
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessageBox } from "element-plus";
import { useUserAuthStore } from "@/store/modules/userAuth";
import {
  type ArticleCommentResponse,
  type CreateCommentRequest,
  UserCommentUtils
} from "@/api/user-comment";

import CommentForm from "./CommentForm.vue";

interface Props {
  comment: ArticleCommentResponse;
  articleId: number;
}

interface Emits {
  (e: "reply", data: CreateCommentRequest): void;
  (e: "like", data: { commentId: number; currentLiked: boolean }): void;
  (e: "delete", commentId: number): void;
  (e: "load-replies", commentId: number): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const userAuthStore = useUserAuthStore();

// 响应式数据
const showReplyForm = ref(false);

// 计算属性
const isLoggedIn = computed(() => userAuthStore.isLoggedIn);
const currentUserId = computed(() => userAuthStore.userInfo?.userId);

const canDelete = computed(() => {
  return (
    isLoggedIn.value && currentUserId.value === props.comment.author?.userId
  );
});

// 方法
const formatTime = (timeStr: string) => {
  return UserCommentUtils.formatTime(timeStr);
};

const formatNumber = (num: number) => {
  return UserCommentUtils.formatNumber(num);
};

const handleLike = () => {
  if (!isLoggedIn.value) {
    return;
  }

  // 获取当前最新的点赞状态
  const currentLikedStatus = props.comment.isLiked;

  console.log("📝 CommentItem点赞事件:", {
    commentId: props.comment.id,
    currentLiked: currentLikedStatus,
    commentObject: props.comment
  });

  // 直接传递评论ID和当前状态，让父组件决定新的点赞状态
  emit("like", {
    commentId: props.comment.id,
    currentLiked: currentLikedStatus
  });
};

const toggleReply = () => {
  if (!isLoggedIn.value) {
    return;
  }

  showReplyForm.value = !showReplyForm.value;
};

const handleReplySubmit = (data: CreateCommentRequest) => {
  emit("reply", data);
  showReplyForm.value = false;
};

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这条评论吗？删除后无法恢复。",
      "确认删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    emit("delete", props.comment.id);
  } catch {
    // 用户取消删除
  }
};
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .comment-item.is-reply {
    padding-left: 12px;
    margin-left: 24px;
  }

  .comment-main {
    gap: 8px;
  }

  .comment-meta {
    flex-wrap: wrap;
    gap: 6px;
  }

  .comment-actions {
    gap: 12px;
  }

  .more-replies {
    padding-left: 24px;
  }
}

@media (width <= 480px) {
  .comment-item.is-reply {
    padding-left: 8px;
    margin-left: 16px;
  }

  .comment-avatar {
    display: none;
  }

  .comment-main {
    gap: 0;
  }

  .more-replies {
    padding-left: 16px;
  }
}

.comment-item {
  margin-bottom: 16px;
}

.comment-item.is-reply {
  padding-left: 16px;
  margin-left: 48px;
  border-left: 2px solid var(--el-border-color-extra-light);
}

.comment-main {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.comment-avatar {
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-meta {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
}

.user-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.reply-to {
  color: var(--el-color-primary);
}

.comment-time {
  color: var(--el-text-color-secondary);
}

.comment-text {
  margin-bottom: 12px;
  line-height: 1.6;
  color: var(--el-text-color-primary);
  word-break: break-word;
}

.comment-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.comment-actions .el-button {
  height: auto;
  padding: 4px 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.comment-actions .el-button:hover {
  color: var(--el-color-primary);
}

.comment-actions .el-button.is-liked {
  color: var(--el-color-primary);
}

.reply-form {
  padding: 16px;
  margin-top: 16px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.comment-replies {
  margin-top: 16px;
}

.more-replies {
  padding-left: 48px;
  margin-top: 12px;
}

.more-replies .el-button {
  font-size: 13px;
  color: var(--el-color-primary);
}
</style>
